import workerpool from "workerpool"
import { input } from "@inquirer/prompts"

import LocalOldOrderList from './pendingOrder.json' with { type: "json" }

const mainWorker = "./mainWorker.js"

async function multiThreadingRun() {
    let pool
    let spinner
    try {
        const maxWorkersStr = await input({ message: "Enter max workers number", required: true })
        const maxWorkers = parseInt(maxWorkersStr)

        if (Number.isNaN(maxWorkers) || maxWorkers <= 0) {
            throw new Error('请输入正确的数字')
        }

        // spinner = ora('正在批量进行流程').start()

        pool = workerpool.pool(mainWorker, {
            maxWorkers: maxWorkers,
        })

        const oneTimeLimit = Math.max(maxWorkers, 50)
        const data = await getLocalOldOrderList(0, oneTimeLimit)

        const oldOrderList = data.data

        const log = []

        const workerList = []
        for (let i = 0; i < 1000; i++) {
            const order = oldOrderList[i % oldOrderList.length]
            const promise = pool
                .exec("test", [order.code, order.oldCode])
                .then(code => log.push(code + ' ' + new Date().toLocaleString()))
            workerList.push(promise)
        }

        await Promise.all(workerList)

        console.log(log)

        spinner?.succeed('全部执行完成')
    } catch (e) {
        spinner?.info(e.message)
    } finally {
        spinner?.stop()
        pool?.terminate()
    }
}

async function getLocalOldOrderList(offset, limit) {
    return {
        total: LocalOldOrderList.length,
        data: LocalOldOrderList.slice(offset, offset + limit)
    }
}

await multiThreadingRun()
